import { cookies } from 'next/headers';
import { ClientInfo, SESSION_COOKIE_NAME, SessionData, VIP_STATUS } from '../types/session';
import { SessionRepository } from '../database/repositories/session-repository';

/**
 * 会话服务 - 提供会话管理相关业务逻辑
 */
export class SessionService {
  /**
   * 初始化会话
   * 获取现有会话或创建新会话
   */
  static async initialize(
    sessionId?: string,
    isVip: boolean = false
  ): Promise<{ session: SessionData; isNew: boolean }> {
    // 尝试获取现有会话
    if (sessionId) {
      const session = await SessionRepository.getById(sessionId);
      if (session && session.expiresAt > new Date()) {
        return { session, isNew: false };
      }
    }
    
    // 创建新会话
    const newSession = await SessionRepository.getOrCreate(undefined, isVip);
    return { session: newSession, isNew: true };
  }

  /**
   * 获取会话数据
   */
  static async getSession(sessionId: string): Promise<SessionData | null> {
    if (!sessionId) return null;
    
    const session = await SessionRepository.getById(sessionId);
    if (!session || session.expiresAt < new Date()) {
      return null;
    }
    
    return session;
  }

  /**
   * 设置VIP状态
   */
  static async setVipStatus(sessionId: string, isVip: boolean): Promise<boolean> {
    try {
      await SessionRepository.setVipStatus(sessionId, isVip);
      return true;
    } catch (error) {
      console.error('设置VIP状态失败:', error);
      return false;
    }
  }

  /**
   * 记录页面访问
   */
  static async recordVisit(sessionId: string, path?: string): Promise<boolean> {
    try {
      await SessionRepository.recordVisit(sessionId, path);
      return true;
    } catch (error) {
      console.error('记录访问失败:', error);
      return false;
    }
  }

  /**
   * 获取VIP状态
   */
  static async getVipStatus(): Promise<number> {
    try {
      const cookieStore = await cookies();
      const sessionCookie = cookieStore.get(SESSION_COOKIE_NAME);
      
      if (!sessionCookie) {
        return VIP_STATUS.NORMAL;
      }
      
      const session = await this.getSession(sessionCookie.value);
      return session?.isVip ? VIP_STATUS.VIP : VIP_STATUS.NORMAL;
    } catch (error) {
      console.error('获取VIP状态失败:', error);
      return VIP_STATUS.NORMAL;
    }
  }
} 